package site.zhouinfo.servlet02;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet获取表单数据
 *
 * @author zhou
 * @create 2017-06-23 15:41
 * @email zhouinfo@qq.com
 * @blog blog.zhouinfo.site
 */
public class ServletForm extends HttpServlet {

    /**
     * 返回响应数据
     *
     * @param req  请求数据
     * @param resp 响应数据
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取路径
        String form = getServletContext().getRealPath("/view/servlet02/form.html");
        // 指定以UTF-8编码读入html文件
        InputStreamReader isr = new InputStreamReader(new FileInputStream(form), "UTF-8");
        BufferedReader br = new BufferedReader(isr);

        // 指定响应数据返回类型及编码
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        String str;
        while ((str = br.readLine()) != null) {
            writer.println(str);
            System.out.println(str);
        }
        //关闭输入流
        br.close();
        //清除缓存
        writer.flush();
    }

    /**
     * 获取请求数据
     *
     * @param req  请求数据
     * @param resp 响应数据
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String nameTransform = new String(name.getBytes("iso8859-1"), "utf-8");
        String password = req.getParameter("password");
        // 获取多选数据
        String[] favors = req.getParameterValues("favor");

        System.out.println("从表单中获取到的name: " + name);
        System.out.println("经过处理的name: " + nameTransform);
        System.out.println("从表单中获取到的password: " + password);
        for (String favor : favors) {
            System.out.println("从表单中获取到的favor:" + favor);
        }
    }
}
